﻿using Blm.Utils.Extensions;
using Blm.Utils.Utility;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace VisionCloud.Utility
{
    /// <summary>
    /// 和文件相关的操作，如获取文件MD5值
    /// </summary>
    public static class FileInfoUtils
    {
        /// <summary>
        /// 相对路径转绝对路径 ,以WebRootPath为基准,支持../
        /// </summary>
        /// <param name="relativePath"></param>
        /// <returns></returns>
        public static string GetAbsolutePathFromRelative(string relativePath)
        {
            relativePath = relativePath.Replace("\\", "/");
            string rootPath = StartupServer.WebRootPath;
            relativePath = relativePath.ToCompatibilityPath();
            while (relativePath.IndexOf("../") > -1)
            {
                relativePath = relativePath.Remove(0, 3);
                rootPath = Directory.GetParent(rootPath).FullName;
            }
            return FileInfoUtil.Combine(rootPath, relativePath);
        }

        public static async Task<string> ReadFileToStringAsync(string path, Encoding encoding)
        {
            var bytes = await File.ReadAllBytesAsync(path);
            return encoding.GetString(bytes);
        }

        public static void SaveJsonFile(string jsonData, string fullName)
        {
            try
            {
                if (!File.Exists(fullName))
                {
                    FileStream fs = new FileStream(fullName, FileMode.Create, FileAccess.ReadWrite);
                    fs.Close();
                }
                File.WriteAllText(fullName, jsonData);
            }
            catch (Exception ex)
            {
                Logger.Info($"保存文件错误：{fullName}", ex);
            }
        }
    }
}